import React, { useState, useEffect, useRef } from 'react'

export default function MapContainer(props) {
  let mapRef = useRef()
  let [clickaddress,setAddress] = useState('')
  useEffect(() => {
    let myMap = window.AMap
    let map = new myMap.Map(mapRef.current, {
      zoom: 11
    });
    var geocoder = new myMap.Geocoder();
    var marker = new myMap.Marker();
    map.on('click', function (e) {
      console.log(e.lnglat)
      let {lng,lat} = e.lnglat
      map.add(marker);
      marker.setPosition([lng,lat]);
      geocoder.getAddress([lng,lat], function (status, result) {
        if (status === 'complete' && result.regeocode) {
          let address = result.regeocode.formattedAddress;
          let {district,township} = result.regeocode.addressComponent
          setAddress(address)
          // console.log(result)
          props.handleAddress({lnglat:[lng,lat],district,township,address})
        } else {
          console.log('根据经纬度查询地址失败')
        }
      });
    })
  }, [])
  return (
    <div>
      <div>{clickaddress} </div>
      <div
        ref={mapRef}
        style={{height:'380px',border:'1px solid #128713'}}
      >
      </div>
    </div>
  )
}
